﻿using System;
using System.Collections.Generic;
using System.Text;

using YouHP.Utility;
using YouHP.Model;
using YouHP.BLL;
using YouHP.Config;
using System.IO;
using YouHP.Model.Group;

namespace YouHP.Pages
{
    public class BasePage : System.Web.UI.Page
    {
        public readonly YouHP.Config.BaseConfig Config = new YouHP.Config.BaseConfig();

        #region 用户基本信息
        protected UserInfo UserData = new UserInfo();// 当前用户的信息
        protected UserGroupInfo UserGroupInfo = new UserGroupInfo(); //当前用户组信息   
        #endregion


        //页面属性
        public String SeoTitle = "优医网 - 全球最先进的病患经验分享与交流平台：分享疾病经验，交流就医信息，病患帮助病患";        
        public String SeoKeywords { get; set;}
        public String SeoDescription { get; set; }
        public String SeoHead { get; set; }
        public string PageTitle { get; set; }
        public string PageName { get; set; }
        public string PageName2 { get; set; }
        public string PageName3 { get; set; }
        public String Meta { get; set; }
        public String Link { get; set; }
        public String Script { get; set; }
        public bool IsPost { get; set; }
        public string AbsolutePath { get; set; }
        public PageKeys PageKey;
        public struct UserMeaasges { public string msgName; public int count;}
        public UserMeaasges[] msgList = new UserMeaasges[7];
        public int MsgCount = 0;


        public void SetTitle(string title)
        {
            PageTitle = title;
            MsgboxShowbackLink = "true";

            SeoKeywords = "医疗,健康,血小板,白血病,病友,病历,治疗,药物,药方,中药,格列卫,强的松,类克,克罗恩,溃疡性结肠炎,骨髓瘤, 特发性血小板减少性紫癜,慢性粒细胞白血病";
        }
        
        
        #region 提示消息
        // 
        public int ErrorCount { get; set; }
        public string MsgboxText = "";
        public String MsgboxUrl = "";
        public string MsgboxShowbackLink { get; set; }
        public string MsgboxBackLink { get; set; }
        public string ContinueToWrite { get; set; }
        
        #endregion

        public DateTime StartTime;
        public string EsacpedSecond 
        {
            get
            {
                TimeSpan span = DateTime.Now - StartTime;
                return string.Format("{0} 毫秒", span.TotalMilliseconds);
            }
        }

        #region 临时变量

        protected StringBuilder templateBuilder = new StringBuilder();
        protected string TempUrl = "";

        #endregion

        #region 页面html函数

        /// <summary>
        /// 设置页面定时转向
        /// </summary>
        public void SetMetaRefresh()
        {
            SetMetaRefresh(2, MsgboxUrl);
        }

        /// <summary>
        /// 设置页面定时转向
        /// </summary>
        /// <param name="sec">时间(秒)</param>
        public void SetMetaRefresh(int sec)
        {
            SetMetaRefresh(sec, MsgboxUrl);
        }

        /// <summary>
        /// 设置页面定时转向
        /// </summary>
        /// <param name="sec">时间(秒)</param>
        /// <param name="url">转向地址</param>
        public void SetMetaRefresh(int sec, string url)
        {
            Meta += string.Format("\r\n <meta http-equiv=\"refresh\" content=\"{0} url={1}\" />", sec, url);
        }

        /// <summary>
        /// 插入指定路径的CSS
        /// </summary>
        /// <param name="url">CSS路径</param>
        public void AddLinkCss(string url)
        {
            Link = Link + "\r\n<link href=\"" + url + "\" rel=\"stylesheet\" type=\"text/css\" charset=\"utf-8\" />";
        }

        public void AddLinkRss(string url, string title)
        {
            Link = Link + "\r\n<link rel=\"alternate\" type=\"application/rss+xml\" title=\"" + title + "\" href=\"" + url + "\" />";

        }

        /// <summary>
        /// 插入指定路径的CSS
        /// </summary>
        /// <param name="url">CSS路径</param>
        public void AddLinkCss(string url, string linkId)
        {
            Link = Link + "\r\n<link href=\"" + url + "\" rel=\"stylesheet\" type=\"text/css\" id=\"" + linkId + "\" />";
        }

        /// <summary>
        /// 插入脚本内容到页面head中
        /// </summary>
        /// <param name="scriptstr">不包括<mScript></mScript>的脚本主体字符串</param>
        public void AddScript(string scriptStr)
        {
            AddScript(scriptStr, "javascript");
        }

        /// <summary>
        /// 插入脚本内容到页面head中
        /// </summary>
        /// <param name="scriptstr">不包括<mScript>
        /// <param name="scripttype">脚本类型(值为：vbscript或javascript,默认为javascript)</param>
        public void AddScript(string scriptStr, string scriptType)
        {
            if (!scriptType.ToLower().Equals("vbscript") && !scriptType.ToLower().Equals("vbscript"))
            {
                scriptType = "javascript";
            }

            Script = Script + "\r\n<script type=\"text/" + scriptType + "\">" + scriptStr + "</script>";
        }

        public void AddScriptSrc(string path)
        {
            if (Script != "") Script += "\r\n";
            Script = Script + "<script type=\"text/javascript\" src=\"" + path + "\"></script>";
        }

        public void AddDatePicker()
        {
            this.AddScriptSrc("/support/My97DatePicker/WdatePicker.js");
        }

        public void AddCommonJS()
        {
            this.AddScriptSrc("/support/common/common.js");
        }

        /// <summary>
        /// 插入指定路径的CSS
        /// </summary>
        /// <param name="metastr">CSS路径</param>
        public void AddMeta(string metaStr)
        {
            Meta = Meta + "\r\n<meta " + metaStr + " />";
        }

        /// <summary>
        /// 增加错误提示
        /// </summary>
        /// <param name="errinfo">错误提示信息</param>            
        public void AddErrLine(string errInfo)
        {
            if (MsgboxText.Length == 0)
            {
                MsgboxText = MsgboxText + errInfo;
            }
            else
            {
                MsgboxText = MsgboxText + "<br />" + errInfo;
            }

            ErrorCount++;
        }

        /// <summary>
        /// 增加提示信息
        /// </summary>
        /// <param name="strinfo">提示信息</param>
        public void AddMsgLine(string strInfo)
        {
            if (MsgboxText.Length == 0)
            {
                MsgboxText = MsgboxText + strInfo;
            }
            else
            {
                MsgboxText = MsgboxText + "<br />" + strInfo;
            }
        }

        /// <summary>
        /// 是否已经发生错误
        /// </summary>
        /// <returns>有错误则返回true, 无错误则返回false</returns>
        public bool IsErr()
        {
            return ErrorCount > 0;
        }

        /// <summary>
        /// 设置要转向的url
        /// </summary>
        /// <param name="strurl">要转向的url</param>
        public void SetUrl(string strUrl)
        {
            MsgboxUrl = GetUrl(strUrl);
        }

        public void SetUrl2(string strUrl)
        {
            MsgboxUrl = strUrl;
        }

        /// <summary>
        /// 设置回退链接的内容
        /// </summary>
        /// <param name="strback">回退链接的内容</param>
        public void SetBackLink(string strBack)
        {
            MsgboxBackLink = strBack;
        }

        /// <summary>
        /// 设置是否显示回退链接
        /// </summary>
        /// <param name="mLink">要显示则为true, 否则为false</param>
        public void SetShowBackLink(bool mLink)
        {
            if (mLink)
            {
                MsgboxShowbackLink = "true";
            }
            else
            {
                MsgboxShowbackLink = "false";
            }
        }

        /// <summary>
        /// 设置是否继续写信
        /// </summary>
        /// <param name="succ">要显示则为true, 否则为false</param>
        public void SetContinueToWrite(bool succ)
        {
            if (succ)
            {
                ContinueToWrite = "true";
            }
            else
            {
                ContinueToWrite = "false";
            }
        }

        #endregion

        #region 页面流程

        public virtual void InitPage()
        {
            
        }

        public BasePage()
        {
            InitPage();

            StartTime = DateTime.Now;

            MsgboxText = "";
            MsgboxUrl = "";
            MsgboxBackLink = "";
            MsgboxShowbackLink = "";
            ContinueToWrite = "";
            IsPost = RequestTools.IsPost();
            PageName = RequestTools.GetPageName();
            PageName2 = RequestTools.GetPageName2();
            PageName3 = RequestTools.GetPageName3();
            AbsolutePath = RequestTools.GetAbsolutePath();

            ShowPage();
        }
        #endregion

        protected virtual void ShowPage()
        {
        
            if (SeoKeywords != "")
            {
                Meta = Meta + "<meta name=\"keywords\" content=\"" + SeoKeywords + "\" />\r\n";
            }

            if (SeoDescription != "")
            {
                Meta = Meta + "<meta name=\"description\" content=\"" + SeoDescription + "\" />\r\n";
            }

            Meta = Meta + SeoHead;
            Link = Script = "";

            ErrorCount = 0;

            /*从cookie中获取用户信息*/
#if GENDATA
            UserData.Id = 1;
            UserData.UserName = 
            "测试用户";
#else
 
            UserData.Id = CookiesTools.GetUserIdCookie();
            if (UserData.Id > 0) //表示永久登陆的用户
            {
                UserData.UserName = CookiesTools.GetUserNameCookie();   //直接从cookie中获取用户名
                if (UserData.UserName.Length <= 0) UserData.Id = -1;    //如果不存在用户名，则为无效的cookie
            }
#endif
            
 
            this.AddLocation("首页", "/Index.aspx");

            if (UserData.Id > 0)
            {


                msgList[0].msgName = "站内消息";
                msgList[0].count = MessageBLL.Instance.GetNewMessageCount(UserData.Id);
                msgList[1].msgName = "留言";
                msgList[1].count = CommentBLL.Instance.GetNewCommentCount(UserData.Id,0);
                msgList[2].msgName = "留言回复";
                msgList[2].count = CommentBLL.Instance.GetNewCommentCount(UserData.Id, 1);
                msgList[3].msgName = "互动";
                msgList[3].count = ActionBLL.Instance.GetNewActionCount(UserData.Id);
                msgList[4].msgName = "好友申请";
                msgList[4].count = FriendBLL.Instance.GetFriendApplyCount(UserData.Id);
                msgList[5].msgName = "日志评论";
                msgList[5].count = LogCommentBLL.Instance.GetNewLogCommentCount(UserData.Id);
                msgList[6].msgName = "日志评论回复";
                msgList[6].count = LogCommentBLL.Instance.GetNewLogCommentReplyCount(UserData.Id);


                for (int i = 0; i < this.msgList.Length; i++)
                {
                    MsgCount += msgList[i].count;
                }
            }
        }

        public void GetMsgCount()
        {

            MsgCount = 0;
            if (UserData.Id > 0)
            {
                msgList[0].msgName = "站内消息";
                msgList[0].count = MessageBLL.Instance.GetNewMessageCount(UserData.Id);
                msgList[1].msgName = "留言";
                msgList[1].count = CommentBLL.Instance.GetNewCommentCount(UserData.Id, 0);
                msgList[2].msgName = "留言回复";
                msgList[2].count = CommentBLL.Instance.GetNewCommentCount(UserData.Id, 1);
                msgList[3].msgName = "互动";
                msgList[3].count = ActionBLL.Instance.GetNewActionCount(UserData.Id);
                msgList[4].msgName = "好友申请";
                msgList[4].count = FriendBLL.Instance.GetFriendApplyCount(UserData.Id);
                msgList[5].msgName = "日志评论";
                msgList[5].count = LogCommentBLL.Instance.GetNewLogCommentCount(UserData.Id);
                msgList[6].msgName = "日志评论回复";
                msgList[6].count = LogCommentBLL.Instance.GetNewLogCommentReplyCount(UserData.Id);

                for (int i = 0; i < this.msgList.Length; i++)
                {

                    MsgCount += msgList[i].count;
                }
            }
        }

        #region 现在位置

        protected List<string> LocationUrls = new List<string>();

        protected List<string> LocationNames = new List<string>();

        protected void AddLocation(string name, string url)
        {
            LocationNames.Add(name);
            LocationUrls.Add(this.GetUrl(url));
        }
        protected void AddUserLocation()
        {
            
        }

        #endregion

        #region url

        public string GetUrl(string url)
        {
            return Config.WebRealPath + url;
        }

        public string GetResource(string res)
        {
            return string.Format("{0}{1}", Config.ResourcePath, res);
        }

        #endregion

        #region Paging

        public string GetPagingString(int curPage, int countPage, string url, string pageTag)
        {
            url = url.TrimEnd(new char[] { '&' });
            url = url.TrimEnd(new char[] { '?' });
            if (url.IndexOf("?") > 0) url += "&";
            else url += "?";
            url += pageTag;
            url += "=";

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("<a href=\"{0}\">首页</a>\r\n", GetUrl(url + "1"));
            int page = curPage - 1;
            if (page > 1) sb.AppendFormat("<a href=\"{0}\">上一页</a>\r\n", GetUrl(url + page));
            for (page = curPage - 4; page < curPage; page++)
            {
                if (page <= 0) continue;
                sb.AppendFormat("<a href=\"{0}\">{1}</a>\r\n", GetUrl(url + page), page);
            }
            sb.AppendFormat("<b>{0}</b>\r\n", page);
            for (page = curPage +1 ; page <= curPage + 4; page++)
            {
                if (page > countPage) continue;
                sb.AppendFormat("<a href=\"{0}\">{1}</a>\r\n", GetUrl(url + page), page);
            }
            page = curPage + 1;
            if (page < countPage) sb.AppendFormat("<a href=\"{0}\">下一页</a>\r\n", GetUrl(url + page));
            page = countPage;
            sb.AppendFormat("<a href=\"{0}\">末页</a>\r\n", GetUrl(url + page));

            sb.Append("<select onchange=\"location.href=this.options[this.selectedIndex].value;\" style=\"width: 80px;\" > \r\n");
            for (page = 1; page <= countPage; page++)
            {
                sb.AppendFormat("<option value=\"{0}\"",GetUrl(url + page));
                if( page == curPage) sb.Append("selected=\"\" ");
                sb.AppendFormat(" >{0}</option> \r\n", page);
            }
            sb.Append("</select>");
            return sb.ToString();
        }

        public string GetPagingString2(int curPage, int countPage, string action,string href)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("<a href=\"{1}({0})\" onclick=\"" + action + "\">首页</a>\r\n", 1, href);
            int page = curPage - 1;
            if (page > 1) sb.AppendFormat("<a href=\"{1}({0})\" onclick=\"" + action + "\">上一页</a>\r\n", page, href);
            for (page = curPage - 4; page < curPage; page++)
            {
                if (page <= 0) continue;
                sb.AppendFormat("<a href=\"{1}({0})\" onclick=\"" + action + "\">{0}</a>\r\n", page, href);
            }
            sb.AppendFormat("<b>{0}</b>\r\n", page);
            for (page = curPage + 1; page <= curPage + 4; page++)
            {
                if (page > countPage) continue;
                sb.AppendFormat("<a href=\"{1}({0})\" onclick=\"" + action + "\">{0}</a>\r\n", page, href);
            }
            page = curPage + 1;
            if (page < countPage) sb.AppendFormat("<a href=\"{1}({0})\" onclick=\"" + action + "\">下一页</a>\r\n", page, href);
            page = countPage;
            sb.AppendFormat("<a href=\"{1}({0})\" onclick=\"" + action + "\">末页</a>\r\n", page, href);

            sb.AppendFormat("<select onchange=\"{1}({0})\"  style=\"width: 80px;\" > \r\n", "this.options[this.selectedIndex].value",href);
            for (page = 1; page <= countPage; page++)
            {
                sb.AppendFormat("<option value=\"{0}\"", page);
                if (page == curPage) sb.Append("selected=\"\" ");
                sb.AppendFormat(" >{0}</option> \r\n", page);
            }
            sb.Append("</select>");
            return sb.ToString();
        }


        public string GetPagingString3(int curPage, int countPage, string action, string href,int para)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("<a href=\"{1}({2},{0})\" onclick=\"" + action + "\">首页</a>\r\n", 1, href,para);
            int page = curPage - 1;
            if (page > 1) sb.AppendFormat("<a href=\"{1}({2},{0})\" onclick=\"" + action + "\">上一页</a>\r\n", page, href, para);
            for (page = curPage - 4; page < curPage; page++)
            {
                if (page <= 0) continue;
                sb.AppendFormat("<a href=\"{1}({2},{0})\" onclick=\"" + action + "\">{0}</a>\r\n", page, href, para);
            }
            sb.AppendFormat("<b>{0}</b>\r\n", page);
            for (page = curPage + 1; page <= curPage + 4; page++)
            {
                if (page > countPage) continue;
                sb.AppendFormat("<a href=\"{1}({2},{0})\" onclick=\"" + action + "\">{0}</a>\r\n", page, href, para);
            }
            page = curPage + 1;
            if (page < countPage) sb.AppendFormat("<a href=\"{1}({2},{0})\" onclick=\"" + action + "\">下一页</a>\r\n", page, href, para);
            page = countPage;
            sb.AppendFormat("<a href=\"{1}({2},{0})\" onclick=\"" + action + "\">末页</a>\r\n", page, href, para);

            sb.AppendFormat("<select onchange=\"{1}({2},{0})\"  style=\"width: 80px;\" > \r\n", "this.options[this.selectedIndex].value", href, para);
            for (page = 1; page <= countPage; page++)
            {
                sb.AppendFormat("<option value=\"{0}\"", page);
                if (page == curPage) sb.Append("selected=\"\" ");
                sb.AppendFormat(" >{0}</option> \r\n", page);
            }
            sb.Append("</select>");
            return sb.ToString();
        }
        #endregion

        public void Redirect(string url)
        {
            ResponseHelper.Redirect(this.GetUrl(url));
        }


    }
}
